<?php
require_once '../includes/functions.php';
check_login();

header('Content-Type: application/json');

$template_name = $_POST['template'] ?? '';
$subdomain = $_POST['subdomain'] ?? '';
$old_filename = $_POST['old_file'] ?? '';

// 至少需要提供一个参数
if ((empty($template_name) && empty($subdomain)) || empty($old_filename)) {
    http_response_code(400);
    echo json_encode(['error' => '参数错误：需要提供template或subdomain参数，以及old_file参数']);
    exit;
}

// 验证文件名格式
if (!preg_match('/^[a-zA-Z0-9-_\.]+$/', $old_filename)) {
    http_response_code(400);
    echo json_encode(['error' => '无效的文件名']);
    exit;
}

// 根据参数类型确定资源路径
if (!empty($subdomain)) {
    // 验证子域名格式
    if (!preg_match('/^[a-zA-Z0-9-]+$/', $subdomain)) {
        http_response_code(400);
        echo json_encode(['error' => '无效的子域名']);
        exit;
    }
    
    $base_dir = "../landing_pages/{$subdomain}";
    $resources_dir = "{$base_dir}/resources";
    // 对于落地页，使用相对于落地页根目录的路径
    $url_prefix = "/landing_pages/{$subdomain}/resources/";
} else {
    // 验证模板名称格式
    if (!preg_match('/^[a-zA-Z0-9-_]+$/', $template_name)) {
        http_response_code(400);
        echo json_encode(['error' => '无效的模板名称']);
        exit;
    }
    
    $template_path = get_template_path($template_name);
    $resources_dir = $template_path . '/resources';
    
    // 检查模板是否存在
    if (!file_exists($template_path) || !is_dir($template_path)) {
        http_response_code(404);
        echo json_encode(['error' => '模板不存在']);
        exit;
    }
    
    $url_prefix = "/templates/{$template_name}/resources/";
}

$old_file_path = $resources_dir . '/' . $old_filename;
$resources_file = $resources_dir . '/resources.json';

// 检查资源目录是否存在
if (!file_exists($resources_dir) || !is_dir($resources_dir)) {
    http_response_code(404);
    echo json_encode(['error' => '资源目录不存在']);
    exit;
}

// 检查旧文件是否存在
if (!file_exists($old_file_path)) {
    http_response_code(404);
    echo json_encode(['error' => '原文件不存在']);
    exit;
}

// 检查是否有文件上传
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => '文件上传失败']);
    exit;
}

$file = $_FILES['file'];
$file_type = $file['type'];

// 检查文件类型
if (!preg_match('/^(image|video)\//', $file_type)) {
    http_response_code(400);
    echo json_encode(['error' => '不支持的文件类型']);
    exit;
}

// 读取资源信息
$resources = [];
if (file_exists($resources_file)) {
    $resources = json_decode(file_get_contents($resources_file), true) ?? [];
}

// 生成新的唯一文件名
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$new_filename = uniqid() . '.' . $extension;
$new_file_path = $resources_dir . '/' . $new_filename;

// 更新资源信息
$resource_updated = false;
foreach ($resources as $key => $resource) {
    if ($resource['filename'] === $old_filename) {
        // 简化类型为'image'或'video'
        $simple_type = strpos($file_type, 'image/') === 0 ? 'image' : 'video';
        
        // 更新资源信息
            // 记录旧缩略图路径
            $old_thumbnail = isset($resource['thumbnail']) ? $resources_dir . '/' . basename($resource['thumbnail']) : null;
            
            $resources[$key] = [
                'filename' => $new_filename,
                'type' => $simple_type,
                'path' => 'resources/' . $new_filename,
                'description' => $file['name'],
                'url' => $url_prefix . $new_filename
            ];

            // 如果是视频文件，生成封面图
            if ($simple_type === 'video') {
                $thumbnail_filename = 'thumb_' . pathinfo($new_filename, PATHINFO_FILENAME) . '.jpg';
                $thumbnail_path = $resources_dir . '/' . $thumbnail_filename;
                
            }
        $resource_updated = true;
        break;
    }
}

if (!$resource_updated) {
    http_response_code(404);
    echo json_encode(['error' => '资源记录不存在']);
    exit;
}

// 上传新文件
try {
    if (!move_uploaded_file($file['tmp_name'], $new_file_path)) {
        throw new Exception('保存文件失败');
    }
    
    // 如果是视频文件，生成封面图
    if ($simple_type === 'video') {
        $thumbnail_filename = 'thumb_' . pathinfo($new_filename, PATHINFO_FILENAME) . '.jpg';
        $thumbnail_path = $resources_dir . '/' . $thumbnail_filename;
        
        // 使用ffmpeg生成封面图
        $ffmpeg_command = "ffmpeg -i \"{$new_file_path}\" -ss 00:00:01 -vframes 1 -q:v 2 \"{$thumbnail_path}\"";
        exec($ffmpeg_command);
        
        if (file_exists($thumbnail_path)) {
            $resources[$key]['thumbnail'] = 'resources/' . $thumbnail_filename;
        }
    }

    // 删除旧文件和旧缩略图
    if (file_exists($old_file_path)) {
        unlink($old_file_path);
    }
    if ($old_thumbnail && file_exists($old_thumbnail)) {
        unlink($old_thumbnail);
    }
} catch (Exception $e) {
    // 清理可能已上传的文件和缩略图
    if (file_exists($new_file_path)) {
        unlink($new_file_path);
    }
    if (isset($thumbnail_path) && file_exists($thumbnail_path)) {
        unlink($thumbnail_path);
    }
    if ($old_thumbnail && file_exists($old_thumbnail)) {
        unlink($old_thumbnail); // 清理可能残留的旧缩略图
    }
    
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
    exit;
}

// 设置文件权限
chmod($new_file_path, 0644);

// 保存更新后的资源信息
if (file_put_contents($resources_file, json_encode($resources, JSON_PRETTY_PRINT)) === false) {
    http_response_code(500);
    echo json_encode(['error' => '保存资源信息失败']);
    exit;
}

echo json_encode([
    'success' => true,
    'message' => '资源替换成功',
    'resource' => $resources[$key]
]);
